package ias.deepsearch.com.helper.service;

import android.accessibilityservice.AccessibilityService;
import android.annotation.TargetApi;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.socks.library.KLog;

/**
 * Created by shawn
 * Data: 2/3/2016
 * Blog: effmx.com
 */
public class DetectionService extends AccessibilityService {

    final static String TAG = "DetectionService_liuyi";

    static String foregroundPackageName;
    static String foregroundActivityName;
    AccessibilityNodeInfo rootNodeInfo;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return Service.START_STICKY_COMPATIBILITY; // 根据需要返回不同的语义值
    }


    /**
     * 重载辅助功能事件回调函数，对窗口状态变化事件进行处理
     * @param event
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {

        int eventType = event.getEventType();
        switch (eventType){
            case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
                 /*
             * 如果 与 DetectionService 相同进程，直接比较 foregroundPackageName 的值即可
             * 如果在不同进程，可以利用 Intent 或 bind service 进行通信
             */
                foregroundPackageName = event.getPackageName().toString();
                foregroundActivityName = event.getClassName().toString();

                //KLog.v(TAG, "foreground pkg: " + foregroundPackageName + " , " + event.getClassName().toString());

            /*
             * 基于以下还可以做很多事情，比如判断当前界面是否是 Activity，是否系统应用等，
             * 与主题无关就不再展开。
             */
                ComponentName cName = new ComponentName(event.getPackageName().toString(),
                        event.getClassName().toString());
                //KLog.v(TAG,cName.getClassName());


                //KLog.v(TAG, "window_state_changed: " + event.getClassName().toString());


                //其实在这里就可以根据Activity名和包名，结合服务器获取到当前页面的领域信息，例如电影页面，但是具体怎么抽取还是有点问题，如果是监听这个事件页面可能页面没加载完，如果监听的是Window_content_changed又会触发很多次，应该怎么处理？


                break;
            //case AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED:
            case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED:


                //KLog.v(TAG, "====window content_changed====");
                retriveContent();

                break;
            default:
                break;
        }

    }


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void retriveContent(){
        rootNodeInfo = getRootInActiveWindow();
//        if(rootNodeInfo == null){
//            KLog.v(TAG, "fail to get the root node");
//            return;
//        }
        //KLog.v(TAG, "root widget----------------------------" + rootNodeInfo.getClassName());
        //recycle(rootNodeInfo);
    }


    public void recycle(AccessibilityNodeInfo info) {
        if (info.getChildCount() == 0) {
            KLog.v(TAG, "child widget----------------------------" + info.getClassName());
            //KLog.v(TAG, "showDialog:" + info.canOpenPopup());
            KLog.v(TAG, "Text：" + info.getText());
            KLog.v(TAG, "windowId:" + info.getWindowId());
        } else {
            KLog.v(TAG, "root widget----------------------------" + info.getClassName());
            for (int i = 0; i < info.getChildCount(); i++) {
                if(info.getChild(i)!=null){
                    recycle(info.getChild(i));
                }
            }
        }
    }

    @Override
    public void onInterrupt() {
    }

    @Override
    protected  void onServiceConnected() {
        super.onServiceConnected();
    }


    /**
     * 方法6：使用 Android AccessibilityService 探测窗口变化，跟据系统回传的参数获取 前台对象 的包名与类名
     *
     * @param packageName 需要检查是否位于栈顶的App的包名
     */
    public static boolean isForegroundPkgViaDetectionService(String packageName) {
        KLog.v("liuyi", packageName + " : " + DetectionService.foregroundPackageName);
        return packageName.equals(DetectionService.foregroundPackageName);
    }

    public static boolean isForegroundActivityDetection(String activityName){
        //TODO 还是会有问题,需要找其他的方式解决判断当前Activity是否在前台的问题 Android 5.0
        KLog.v("liuyi", activityName + " : " + DetectionService.foregroundActivityName);
        return activityName.equals(DetectionService.foregroundActivityName);
    }

    /**
     * 此方法用来判断当前应用的辅助功能服务是否开启
     *
     * @param context
     * @return
     */
    public static boolean isAccessibilitySettingsOn(Context context) {
        int accessibilityEnabled = 0;
        try {
            accessibilityEnabled = Settings.Secure.getInt(context.getContentResolver(),
                    android.provider.Settings.Secure.ACCESSIBILITY_ENABLED);
        } catch (Settings.SettingNotFoundException e) {
            KLog.v("liuyi", e.getMessage());
        }

        if (accessibilityEnabled == 1) {
            String services = Settings.Secure.getString(context.getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            if (services != null) {
                return services.toLowerCase().contains(context.getPackageName().toLowerCase());
            }
        }
        return false;
    }
}